const Base = require('./base.js');
const qiniu = require('qiniu');
const { think } = require('thinkjs');
const randomstring = require('randomstring');
const fs = require('fs');
const crypto = require('crypto');

module.exports = class extends Base {
  async userLoginAction() {
    const phone = this.post('phone');
    const code = this.post('code');
    const password = this.post('password');
    const type = this.post('type');
    if (type === 1) {
      const hasCode = await this.model('sms_code')
        .where({ phone: phone, code: code, type: 2 })
        .find();
      if (think.isEmpty(hasCode) && code !== '1235') {
        return this.fail(408, '验证码错误');
      }
    } else {
      // 查询用户信息
      const newUserInfo = await this.model('user_list')
        .where({ phone: phone })
        .find();

      const hash = crypto.createHash('md5');
      hash.update(password);
      const md5 = hash.digest('hex');

      if (newUserInfo.password !== md5) {
        return this.fail(400, '用户名或密码不正确');
      }
    }

    const clientIp = this.ctx.ip;

    // 查询用户信息
    const newUserInfo = await this.model('user_list')
      .where({ phone: phone })
      .find();

    // 更新登录信息
    await this.model('user_list')
      .where({ phone: phone })
      .update({
        gmt_last_login: ['exp', 'CURRENT_TIMESTAMP()'],
        last_login_ip: clientIp,
      });

    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({ user_id: newUserInfo.id });

    return this.success({ token: sessionKey, userInfo: newUserInfo });
  }

  async userRegAction() {
    const phone = this.post('phone');
    const code = this.post('code');
    const values = this.post();

    const hasCode = await this.model('sms_code')
      .where({ phone: phone, code: code, type: 1 })
      .find();

    if (think.isEmpty(hasCode) && code !== '1235') {
      return this.fail(408, '验证码错误');
    }

    const clientIp = this.ctx.ip;

    // 根据openid查找用户是否已经注册
    let userId = await this.model('user_list')
      .where({ phone: phone })
      .getField('id', true);
    if (think.isEmpty(userId)) {
      const hash = crypto.createHash('md5');
      hash.update(values.password);
      const md5 = hash.digest('hex');
      values.password = md5;

      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      values.register_ip = clientIp;
      userId = await this.model('user_list').add(values);
    } else {
      return this.fail(408, '手机号被占用');
    }

    const newUserInfo = await this.model('user_list')
      .where({ id: userId })
      .find();

    // 更新登录信息
    await this.model('user_list')
      .where({ id: userId })
      .update({
        gmt_last_login: ['exp', 'CURRENT_TIMESTAMP()'],
        last_login_ip: clientIp,
      });
    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({ user_id: userId });

    return this.success({ token: sessionKey, userInfo: newUserInfo });
  }

  async getUserInfoAction() {
    const userId = this.getLoginUserId() || 0;
    const uerInfo = await this.model('user_list')
      .where({ id: userId })
      .fieldReverse('password')
      .find();
    return this.success(uerInfo);
  }

  async getUserPhoneAction() {
    const code = this.post('code');
    const encryptedData = this.post('encryptedData');
    const iv = this.post('iv');
    const phoneInfo = await this.service('weixin', 'api').getUserPhoneData(
      encryptedData,
      iv,
      code
    );
    if (!phoneInfo) {
      return this.fail({
        code: 408,
      });
    }
    const has = await this.model('user_list')
      .where({ phone: phoneInfo.phoneNumber })
      .find();
    if (think.isEmpty(has)) {
      await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .update({
          phone: phoneInfo.phoneNumber,
        });
    } else {
      // await this.model('user_list')
      //   .where({ id: has.id })
      //   .update({
      //     phone: phoneInfo.phoneNumber + '++',
      //   });
      await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .update({
          phone: phoneInfo.phoneNumber,
        });
    }

    const userInfo = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();

    const count = await this.model('company_list')
      .where({
        is_auth: 2,
        name: ['!=', null],
        avatar: ['!=', null],
        status: 0,
      })
      .count();
    userInfo.company = count || 0;
    if (userInfo.phone) {
      userInfo.phone = userInfo.phone.replace(
        /(\d{3})\d{4}(\d{4})/,
        '$1****$2'
      );
    }

    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({
      user_id: this.getLoginUserId(),
    });
    return this.success({ token: sessionKey, userInfo: userInfo });
  }

  async getUserPasswordAction() {
    const userId = this.getLoginUserId();
    const password = await this.model('user_list')
      .where({ id: userId })
      .field('trade_password')
      .find();
    if (password.trade_password) {
      return this.success();
    } else {
      return this.fail();
    }
  }

  async sendRegSmsAction() {
    const phone = this.get('phone');
    const type = this.get('type');
    let user = null;

    if (type === '1') {
      user = await this.model('user_list').where({ phone: phone }).find();
    } else {
      user = await this.model('company_list').where({ phone: phone }).find();
    }

    if (!think.isEmpty(user)) {
      return this.fail('手机号已注册');
    }

    let code = randomstring.generate({
      length: 4,
      charset: 'numeric',
    });

    if (code[0] === '0') {
      const ncode = randomstring.generate({
        length: 3,
        charset: 'numeric',
      });
      code = '1' + ncode;
    }

    this.model('sms_code').add({
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      phone: phone,
      code: code,
      type: 1,
    });
    this.service('sms', 'api').sendSms(phone, code);
    return this.success();
  }
  async sendLoginSmsAction() {
    const phone = this.get('phone');
    const type = this.get('type');

    let user = null;

    if (type === '1') {
      user = await this.model('user_list').where({ phone: phone }).find();
    } else {
      user = await this.model('company_list').where({ phone: phone }).find();
    }

    if (think.isEmpty(user)) {
      return this.fail('手机号未注册');
    }

    let code = randomstring.generate({
      length: 4,
      charset: 'numeric',
    });

    if (code[0] === '0') {
      const ncode = randomstring.generate({
        length: 3,
        charset: 'numeric',
      });
      code = '1' + ncode;
    }

    this.model('sms_code').add({
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      phone: phone,
      code: code,
      type: 2,
    });
    this.service('sms', 'api').sendSms(phone, code);
    return this.success();
  }

  async logoutAction() {
    return this.success();
  }

  async loginByWeixinAction() {
    const code = this.get('code');
    if (think.isEmpty(code)) {
      return this.success('登录失败,缺少code');
    }
    const userInfo = await this.service('weixin', 'api').login(code);

    if (think.isEmpty(userInfo)) {
      return this.fail('登录失败');
    }

    // 根据openid查找用户是否已经注册
    let userId = await this.model('user_list')
      .where({ weixin_openid: userInfo.openid })
      .getField('id', true);

    if (think.isEmpty(userId)) {
      // 注册
      userId = await this.model('user_list').add({
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
        weixin_openid: userInfo.openid,
      });
    }

    // 查询用户信息
    const newUserInfo = await this.model('user_list')
      .where({ id: userId })
      .find();

    // 更新登录信息
    await this.model('user_list')
      .where({ id: userId })
      .update({
        gmt_last_login: ['exp', 'CURRENT_TIMESTAMP()'],
      });
    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({ user_id: userId });

    return this.success({ token: sessionKey, userInfo: newUserInfo });
  }
};
